﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp
{
    public class demo_yield
    {
        //从0遍历到20(不包括20)，输出遍历到的每个元素，
        //并将大于2的所有数字放到一个IEnumerable<int>中返回

        #region ----------------方法一----------------
        private IEnumerable<int> WithNoYield()
        {
            IList<int> list = new List<int>();
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(i.ToString());
                if (i > 2)
                {
                    list.Add(i);
                }
            }
            return list;
        }
        #endregion

        #region ----------------方法二----------------
        private IEnumerable<int> WithYield()
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(i.ToString());
                if (i > 2)
                {
                    yield return i;
                }
            }
        }
        #endregion

        public void demo()
        {
            WithYield();
            WithNoYield();
            foreach (int i in WithNoYield())
            {
                Console.WriteLine(i.ToString());
            }
            foreach (int i in WithYield())
            {
                Console.WriteLine(i.ToString());
            }
        }
    }
}
